<template>
    <div class="asset-ledger">
        <el-card shadow="hover">
            <div class="header">
                <el-input v-model="searchName" placeholder="搜索设备名称/编号" clearable style="width:240px;margin-right:16px;"
                    @keyup.enter="doSearch" />
                <el-select v-model="searchType" placeholder="设备类型" clearable style="width:160px;margin-right:16px;">
                    <el-option v-for="item in typeOptions" :key="item" :label="item" :value="item" />
                </el-select>
                <el-select v-model="searchStatus" placeholder="状态" clearable style="width:140px;margin-right:16px;">
                    <el-option v-for="item in statusOptions" :key="item.value" :label="item.label"
                        :value="item.value" />
                </el-select>
                <el-button type="primary" @click="doSearch">搜索</el-button>
                <el-button type="success" @click="handleAdd" style="margin-left:24px;">新增资产</el-button>
            </div>
            <el-table :data="filteredList" border style="margin-top:18px;">
                <el-table-column prop="id" label="编号" width="150px" align="center" />
                <el-table-column prop="name" label="设备名称" width="170px" align="center" />
                <el-table-column prop="type" label="设备类型" width="170px" align="center" />
                <el-table-column prop="department" label="归属部门" width="170px" align="center" />
                <el-table-column prop="status" label="状态" width="100px" align="center">
                    <template #default="scope">
                        <el-tag :type="statusTagType(scope.row.status)" size="small">{{ scope.row.status }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="buyDate" label="购置日期" width="200px" align="center" />
                <el-table-column label="操作" width="200px" align="center">
                    <template #default="scope">
                        <el-button size="small" type="info" text @click="toDetail(scope.row)">详情</el-button>
                        <el-button size="small" type="primary" text @click="handleEdit(scope.row)">编辑</el-button>
                        <el-button size="small" type="danger" text @click="handleDelete(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
        <!-- 新增/编辑弹窗 -->
        <el-dialog v-model="dialogVisible" :title="dialogTitle" width="400px" destroy-on-close>
            <el-form :model="editRow" :rules="formRules" ref="formRef" label-width="90px">
                <el-form-item label="设备名称" prop="name">
                    <el-input v-model="editRow.name" />
                </el-form-item>
                <el-form-item label="设备类型" prop="type">
                    <el-select v-model="editRow.type" placeholder="请选择">
                        <el-option v-for="item in typeOptions" :key="item" :label="item" :value="item" />
                    </el-select>
                </el-form-item>
                <el-form-item label="归属部门" prop="department">
                    <el-input v-model="editRow.department" />
                </el-form-item>
                <el-form-item label="状态" prop="status">
                    <el-select v-model="editRow.status" placeholder="请选择">
                        <el-option v-for="item in statusOptions" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="购置日期" prop="buyDate">
                    <el-date-picker v-model="editRow.buyDate" type="date" value-format="YYYY-MM-DD"
                        style="width:100%;" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitEdit">确定</el-button>
            </template>
        </el-dialog>
        <el-dialog v-model="confirmDeleteVisible" title="提示" width="340px" center destroy-on-close>
            <div style="font-size:16px;">确定要删除该资产？</div>
            <template #footer>
                <el-button @click="cancelDelete">取消</el-button>
                <el-button type="danger" @click="confirmDelete">确定</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, Ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
const router = useRouter()


// 类型定义
interface Asset {
    id: number
    name: string
    type: string
    department: string
    status: string
    buyDate: string
}

// 模拟类型、状态
const typeOptions: string[] = ['空调主机', '空气净化器', '电梯', '照明系统', '水泵', '配电柜']
const statusOptions: { label: string, value: string }[] = [
    { label: '正常', value: '正常' },
    { label: '维护', value: '维护' },
    { label: '故障', value: '故障' },
    { label: '报废', value: '报废' }
]

// 生成模拟数据
const rawList = ref<Asset[]>(Array.from({ length: 15 }, (_, i) => ({
    id: 1001 + i,
    name: ['中央空调', '新风主机', '电梯', '消防泵', '净水设备'][i % 5] + (i + 1),
    type: typeOptions[i % typeOptions.length],
    department: ['工程部', '后勤部', '物业部'][i % 3],
    status: statusOptions[i % statusOptions.length].value,
    buyDate: `2021-0${(i % 9) + 1}-${(10 + i) % 28 + 1}`.replace(/-(\d)\b/g, '-0$1')
})))

// 搜索条件
const searchName = ref<string>('')
const searchType = ref<string>('')
const searchStatus = ref<string>('')

// 过滤后的数据
const filteredList = computed<Asset[]>(() => {
    let arr = rawList.value
    if (searchName.value) {
        arr = arr.filter(r => r.name.includes(searchName.value) || String(r.id).includes(searchName.value))
    }
    if (searchType.value) {
        arr = arr.filter(r => r.type === searchType.value)
    }
    if (searchStatus.value) {
        arr = arr.filter(r => r.status === searchStatus.value)
    }
    return arr
})

function doSearch(): void { }

// 弹窗相关
const dialogVisible = ref<boolean>(false)
const dialogTitle = ref<string>('新增资产')
const editRow = reactive<Asset>({
    id: 0, name: '', type: '', department: '', status: '', buyDate: ''
})
const formRef = ref<FormInstance>()
const formRules: FormRules = {
    name: [{ required: true, message: '必填', trigger: 'blur' }],
    type: [{ required: true, message: '必选', trigger: 'change' }],
    department: [{ required: true, message: '必填', trigger: 'blur' }],
    status: [{ required: true, message: '必选', trigger: 'change' }],
    buyDate: [{ required: true, message: '必选', trigger: 'change' }]
}

function handleAdd(): void {
    dialogTitle.value = '新增资产'
    Object.assign(editRow, { id: 0, name: '', type: '', department: '', status: '', buyDate: '' })
    dialogVisible.value = true
}

function handleEdit(row: Asset): void {
    dialogTitle.value = '编辑资产'
    Object.assign(editRow, row)
    dialogVisible.value = true
}

function submitEdit(): void {
    formRef.value?.validate((valid: boolean) => {
        if (!valid) return
        if (editRow.id) {
            // 编辑
            const idx = rawList.value.findIndex(r => r.id === editRow.id)
            if (idx !== -1) rawList.value[idx] = { ...editRow }
            ElMessage.success('编辑成功')
        } else {
            // 新增
            editRow.id = rawList.value.length ? Math.max(...rawList.value.map(r => r.id)) + 1 : 1001
            rawList.value.unshift({ ...editRow })
            ElMessage.success('新增成功')
        }
        dialogVisible.value = false
    })
}

const confirmDeleteVisible = ref(false)
const deleteTarget = ref<Asset | null>(null)

function handleDelete(row: Asset) {
    deleteTarget.value = row
    confirmDeleteVisible.value = true
}
function confirmDelete() {
    if (deleteTarget.value && deleteTarget.value.id !== undefined) {
        rawList.value = rawList.value.filter(r => r.id !== deleteTarget.value!.id)
        ElMessage.success('删除成功')
    }
    confirmDeleteVisible.value = false
}
function cancelDelete() {
    confirmDeleteVisible.value = false
}
function toDetail(row: Asset) {
    router.push(`/device/profile/${row.id}`)
}

// 状态tag类型
function statusTagType(status: string): 'success' | 'warning' | 'danger' | 'info' | 'primary' {
    switch (status) {
        case '正常': return 'success'
        case '维护': return 'warning'
        case '故障': return 'danger'
        case '报废': return 'info'
        default: return 'primary'
    }
}
</script>


<style scoped>
.asset-ledger {
    padding: 24px;
}

.header {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    margin-bottom: 6px;
}

.el-table th {
    background: #f8fafc;
}

.el-table .el-tag {
    min-width: 56px;
    text-align: center;
}
</style>
